<template>
  <el-container>
    <el-aside width="300px" class="content-left-list">
      <div class="ps-panel nav-left-menu" style="height: 100%">
        <div class="ps-panel-head">
          <i class="ps-panel-head-icon iconfont icon-guanxiwajue"></i>
          <span class="ps-panel-head-title">关系信息</span>
        </div>

        <div class="ps-panel-body">
          <el-tree :data="labels" node-key="id" default-expand-all :expand-on-click-node="false"
            :props="{ label: 'label_name' }" @node-click="treeNodeClick" :highlight-current="true" ref="visualTree">
          </el-tree>
          <!--<el-menu :default-active="nodeTypes[0].node" class="el-menu-vertical">-->
          <!--<el-menu-item v-for="item of nodeTypes" :index="item.node" :key="item.node" @click="init(item.node)">{{item.node_name}}</el-menu-item>-->
          <!--</el-menu>-->
        </div>
      </div>
    </el-aside>
    <el-main>
      <!-- <div id="neo4jd3" class="neo4jd3"></div> -->
      <!--左侧属性列表 start-->
      <div class="height-100" style="position: absolute; z-index: 1200">
        <leftTreeSider :attrlist="attrlist" ref="leftAttr" :leftAttr_status="isAttr"></leftTreeSider>
      </div>
      <!--左侧属性列表 end-->
      <g6-model class="neo4jd3" ref="g6" @TouchWindow="TouchWindow" @changePage="changePage" :paginations="paginations">
      </g6-model>
    </el-main>
  </el-container>
</template>

<!--<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>-->
<script>
  import G6Model from "../../G6Common/G6Model";
  import leftTreeSider from "../../G6Common/leftTreeSider";
  import $ from "jquery";

  export default {
    name: "index",
    components: {
      G6Model,
      leftTreeSider,
    },
    data: function () {
      return {
        labels: [],

        paginations: {
          pageIndex: 1, // 当前位于哪页
          pageSize: 10, // 页显示多少条
          total: 0, // 总数
          layout: "total, prev, pager, next", // 翻页属性
        },

        // 选中的模型Id和labelName
        currModelId: 0,
        currModelLabelName: "",
        //当前模型的属性信息
        currModelProperties: [],

        //当前选中模型的实例列表
        currModelInstances: [],

        //当前选中的实例信息
        currModelInstance: {
          visible: false,
          rules: {
            名称: [{
              required: true,
              message: "名称不能为空"
            }],
            // dataType: [{required: true, message: '数据类型不能为空'}],
            // createDate: [{required: true, message: '创建时间不能为空'}]
          },
          data: {},
        },
        isAttr: false,
        attrlist: [], //属性表单
      };
    },
    methods: {
      mysleep(time) {
        return new Promise((resolve) => setTimeout(resolve, time));
      },

      treeNodeClick(data) {
        this.currModelId = data.id;
        this.currModelLabelName = data.label_name;
        console.log("nnnnnnnnnnnnnnnnnn", this.currModelLabelName);

        //获取模型属性信息
        this.$store.dispatch("ajax", {
          url: "services/app-zonghe/api/dicLabelProperties?labelId.equals=" +
            this.currModelId +
            "&paged=false",
          method: "get",
          data: {},
          succeed: (res) => {
            console.log(res)
            // //异步执行 所有方法默认都是异步执行
            // this.mysleep(3000).then(() => {
            //     //code 添加三秒后执行的逻辑
            //     console.log('sleep 30 .............');
            // })

            // //执行函数内部同步执行 外面为异步
            // (async function(sleepFunc) {
            //     console.log('Do some thing, ' + new Date());
            //     await sleepFunc(3000);
            //     console.log('Do other things, ' + new Date());
            // })(this.mysleep);

            // //同步执行
            // await this.mysleep(3000).then(() => {
            //     //code 添加三秒后执行的逻辑
            //     console.log('sleep 30 .............');
            // })

            this.currModelProperties = res;
            console.log("get properties: ", this.currModelProperties);
          },
        });

        this.getModelInstances(1);
      },
      //获取当前选中模型的节点--关系
      getModelInstances(pageIndex) {
        if (pageIndex === undefined) {
          pageIndex = this.paginations.pageIndex;
        } else {
          this.paginations.pageIndex = pageIndex;
        }

        this.$store.dispatch("ajaxEx", {
          // url:
          //     "services/app-zonghe/api/example/cypher/nodes/" +
          //     this.currModelLabelName,
          url: "services/app-zonghe/api/example/g6_dataformat/relationships_and_nodes/" +
            this.currModelLabelName +
            "/_search?page=" +
            (pageIndex - 1) +
            "&size=" +
            this.paginations.pageSize,
          method: "post",
          // data: {page: pageIndex - 1, size: this.paginations.pageSize},
          data: {
            node: {
              where: {
                bool_and: [],
              },
            },
            relationship: {
              where: {
                bool_and: [],
              },
            },
          },
          succeed: (res) => {
            console.log("333333333333333333333", res);
            this.currModelInstances = res.data.data;
            if (res.data.data.length == 0) {
              this.$message.error("暂无节点!");
            }
            if (pageIndex > 1) {
              this.$refs["g6"].oneexpand(res.data.data);
            } else {
              this.$refs["g6"].loadTreeSub(res.data.data);
            }
            this.paginations.total = parseInt(res.headers["x-total-count"]);
          },
        });
      },
      //下一页
      changePage(type, index) {
        let pagenum = index;
        if (type == 'next') {
          pagenum = index + 1;
        } else {
          pagenum = index - 1;
        }
        this.paginations.pageIndex = pagenum;
        this.getModelInstances(pagenum);
      },
      showOrEdit(row) {
        console.log("show or edit instance ................. ", row);
        this.currModelInstance.visible = true;
        this.currModelInstance.data = this.clone(row);
      },
      delInstance(row) {
        console.log(
          "del instance ................. ",
          row,
          this.currModelLabelName
        );
        // this.delPopoverClose('del_popover_'+row.id);
        this.$store.dispatch("ajax", {
          url: "services/app-zonghe/api/example/cypher/nodes/" +
            this.currModelLabelName +
            "/" +
            row.id,
          method: "delete",
          data: {},
          succeed: () => {
            this.getModelInstances();
            this.$message.success("删除成功");
            this.delPopoverClose("del_popover_" + row.id);
          },
        });
      },
      addModelInstance() {
        this.currModelInstance.visible = true;
        this.currModelInstance.data = {
          id: 0,
          labels: [this.currModelLabelName],
        };
      },
      saveModelInstance() {
        this.$refs.currModelInstance.validate((valid) => {
          if (valid) {
            if (this.currModelInstance.data.id === 0) {
              this.$store.dispatch("ajax", {
                url: "services/app-zonghe/api/example/cypher/nodes/" +
                  this.currModelLabelName,
                method: "post",
                data: this.currModelInstance.data,
                succeed: () => {
                  this.getModelInstances();
                  this.$message.success("保存成功");
                  this.currModelInstance.visible = false;
                  this.$refs.currModelInstance.resetFields();
                },
              });
            } else {
              // this.currModelInstance.data['labels'].push('BBB测试模型');
              // console.log('update ....: ', this.currModelInstance.data)
              this.$store.dispatch("ajax", {
                url: "services/app-zonghe/api/example/cypher/nodes/" +
                  this.currModelLabelName,
                method: "put",
                data: this.currModelInstance.data,
                succeed: () => {
                  this.getModelInstances();
                  this.$message.success("保存成功");
                  this.currModelInstance.visible = false;
                  this.$refs.currModelInstance.resetFields();
                },
              });
            }
          }
        });
      },

      delPopoverShow(ref) {
        this.$refs[ref].doShow();
      },
      delPopoverClose(ref) {
        this.$refs[ref].doClose();
      },

      checkType(any) {
        return Object.prototype.toString.call(any).slice(8, -1);
      },
      clone(any) {
        let retType = this.checkType(any);
        if (retType === "Object") {
          // 拷贝对象
          let o = {};
          for (let key in any) {
            o[key] = this.clone(any[key]);
          }
          return o;
        } else if (retType === "Array") {
          // 拷贝数组
          var arr = [];
          for (let i = 0, leng = any.length; i < leng; i++) {
            arr[i] = this.clone(any[i]);
          }
          return arr;
        } else if (retType === "Function") {
          // 拷贝函数
          return new Function("return " + any.toString()).call(this);
        } else if (retType === "Date") {
          // 拷贝日期
          return new Date(any.valueOf());
        } else if (retType === "RegExp") {
          // 拷贝正则
          return new RegExp(any);
        } else if (retType === "Map") {
          // 拷贝Map 集合
          let m = new Map();
          any.forEach((v, k) => {
            m.set(k, this.clone(v));
          });
          return m;
        } else if (retType === "Set") {
          // 拷贝Set 集合
          let s = new Set();
          for (let val of any.values()) {
            s.add(this.clone(val));
          }
          return s;
        }
        return any;
      },

      initLabels() {
        this.$store.dispatch("ajax", {
          url: "services/app-zonghe/api/dicLabel/tree?type.equals=5",
          method: "get",
          succeed: (res) => {
            this.labels = res;
            this.currModelLabelName = res[0].type;
            // console.log(this.$refs.visualTree);
            // setTimeout(() => {
            //   this.$refs.visualTree.setCurrentKey(res[0].id);
            // }, 1000);

            // this.getModelInstances(1);
          },
        });
      },
      //触发打开关闭属性表单
      TouchWindow(isShow, data) {
        console.log(isShow, data);
        this.isAttr = isShow;
        if (isShow) {
          this.attrlist = data.attrs;
        } else {
          this.attrlist = [];
        }
      },
    },
    mounted() {
      this.initLabels();
    },
  };
</script>
<style lang="less">
  .neo4jd3 {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

  .el-main {
    position: relative;
  }
</style>